<?php

namespace app\admin\model\goods;

use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;

    

    // 表名
    protected $table = 'goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'stock_type_text',
        'dispatch_type_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    
    public function getStatusList()
    {
        return ['up' => __('Status up'), 'hidden' => __('Status hidden'), 'down' => __('Status down')];
    }

    public function getStockTypeList()
    {
        return ['place' => __('Stock_type place'), 'pay' => __('Stock_type pay')];
    }

    public function getDispatchTypeList()
    {
        return ['express' => __('Dispatch_type express')];
        return ['express' => __('Dispatch_type express'), 'ziti' => __('Dispatch_type ziti')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStockTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['stock_type']) ? $data['stock_type'] : '');
        $list = $this->getStockTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDispatchTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['dispatch_type']) ? $data['dispatch_type'] : '');
        $valueArr = explode(',', $value);
        $list = $this->getDispatchTypeList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }

    protected function setDispatchTypeAttr($value)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }



    public function category()
    {
        return $this->belongsTo('app\common\model\Category','cate_id','id');
    }

    public function spec()
    {
        return $this->hasMany('app\common\model\goods\GoodsSpecModel','goods_id','id');
    }
}
